//
//  CZRefreshControl.swift
//  weibo27
//
//  Created by mac on 16/4/20.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
let WBRefreshControlOffset :CGFloat = -60

/*
MARK: KVO 监听方法
1 刷新控件始终待在屏幕上
2 下拉的时候，frame 的 y一直变小 相反（向上推）一直变大
3 默认的 y值是 0
*/
class CZRefreshControl: UIRefreshControl {

   override func endRefreshing(){
    
        super.endRefreshing()
        
        refresheView.stopAni()
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refresheView.startAnima()
    }
    
    // MARK: - 构造函数
    override init() {
        super.init()
        
        tintColor = UIColor.clearColor()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    private func setupUI(){
        //1 添加控件
        addSubview(refresheView)
        
        //2 设置frame  使用xib加载要指定控件的大小
        refresheView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refresheView.bounds.size)
        }
        
        //3 使用KVO监听属性值的变化 
        // 挡主线程中有任务，就不会调度队列中的任务执行
        // 让当前运行循环中所有的代码执行完毕后，运行循环结束前，开始监听
        // 方法的触发会在下一次运行循环开始
        dispatch_async(dispatch_get_main_queue()) {
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    /// 懒加载刷新控件
    private lazy var refresheView:RefreshView = RefreshView.refreshView()
    
    // MARK: 使用KVO监听属性值的变化
    //箭头旋转标志
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //如果是向上翻转就不做操作
        if frame.origin.y>0{
            return
        }
        
        //如果正在动画就返回
        if refreshing {
            
            refresheView.startAnima()
            return
        }
        
        if (frame.origin.y<WBRefreshControlOffset) && !refresheView.rotateFlag{
//            print("翻转过去")
            refresheView.rotateFlag = true
            
        }else if (frame.origin.y>=WBRefreshControlOffset) && refresheView.rotateFlag{
//            print("在转回去")
            refresheView.rotateFlag = false
            
        }
        
//        print(frame)
    }
    
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }


}


class RefreshView: UIView {
    
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipImageView: UIImageView!
    class func refreshView() -> RefreshView{
        
        //根据nib的名称加载视图
        let nib = UINib(nibName: "CZRefreshControl", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil)[0] as! RefreshView
    }
    
    var rotateFlag = false{
        didSet{
            rotateTipIcon()
        }
    }
    
    private func rotateTipIcon(){
        
        var angel = CGFloat(M_PI)
        angel += rotateFlag ? -0.0001 : 0.0001
     //旋转180   //旋转动画：顺时针有限 + 就近原则
      UIView.animateWithDuration(0.5) { () -> Void in
         self.tipImageView.transform = CGAffineTransformRotate(self.tipImageView.transform, CGFloat(angel))
        }
    }
    
    ///开始刷新动画
    private func startAnima(){
        tipView.hidden = true
        
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil{
//            print("已经开始刷新")
            return
        }
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        loadingIconView.layer.addAnimation(anim, forKey: key)
        
        
    }
    ///结束刷新数据
    
    private func stopAni(){
        
        tipView.hidden = false
        
        loadingIconView.layer.removeAllAnimations()
    }
}





















